<!--
 * @Description: 展示电影订单
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-09-24 17:45:00
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view>
    <!-- 展示订单状态 -->
    <view class="top">
      <van-tabs
        :active="current"
        @change="handleOrderChange"
        color="#FF6C18"
        title-inactive-color="#666"
        title-active-color="#FF6C18"
      >
        <van-tab :title="`${zt.name}`" v-for="zt in stateList"></van-tab>
      </van-tabs>
      <view style="text-align: right; margin: 20rpx">
        <!-- 重新加载图标 -->
        <u-icon
          color="black"
          name="reload"
          size="40"
          @click="handleGetOrder"
          style="cursor: pointer"
        ></u-icon>
      </view>
    </view>
    <view class="footer">
      <template v-if="orderArr.length > 0">
        <view
          class="item"
          v-for="ddItem in orderArr"
          :key="ddItem.id"
          @click="handleClickItem(ddItem)"
        >
          <view class="item-t">
            <view class="yymc overwz" style="width: 500rpx">{{
              ddItem.orderThirdParty.cinemaName
            }}</view>
            <view class="zswz" v-if="current == 0 || current == 2">
              <text style="color: #1a73e8">{{
                handleText(ddItem.status, ddItem.orderThirdParty.orderStatus)
              }}</text>
            </view>
          </view>
          <view class="item-b">
            <view class="item-l">
              <van-image
                width="100%"
                height="232rpx"
                :src="ddItem.orderThirdParty.posterUrl"
              />
            </view>
            <view class="item-r">
              <view class="nr">
                <view class="bt overwz">
                  {{ ddItem.orderThirdParty.movieName }}
                </view>
                <view class="hswz overwz">{{
                  ddItem.orderThirdParty.hallName
                }}</view>
                <view class="hswz overwz" style="margin: 10rpx 0">
                  {{ ddItem.orderThirdParty.seatsInfos.replaceAll('列', '座') }}
                </view>
                <view class="hswz" style="margin-bottom: 50rpx">{{
                  ddItem.orderThirdParty.showTime
                }}</view>
                <view class="tswz">
                  <text class="hswz"
                    >共{{ ddItem.orderProductSkus.length }}张</text
                  >
                  <text style="color: #000; padding: 0 10rpx">{{
                    handleFkwz(ddItem.status)
                  }}</text>
                  <text class="jq"
                    >¥{{
                      (ddItem.totalMoney - ddItem.scoreMoney).toFixed(2)
                    }}</text
                  >
                </view>
              </view>
              <!-- 已放映图片 -->
              <view class="fybox">
                <u-image
                  v-if="ddItem.status == 60 && ddItem.isfy == true"
                  src="../../static/yfy.png"
                  width="80rpx"
                  height="80rpx"
                ></u-image>
              </view>
            </view>
          </view>
          <view
            style="text-align: right; margin-bottom: 10rpx; font-size: 24rpx"
          >
            购买时间：{{ formatTimestamp(ddItem.createTime) }}</view
          >
          <view
            v-if="ddItem.orderThirdParty.cinemaClose == 1"
            style="color: red; margin-bottom: 20rpx"
          >
            <text style="margin-right: 20rpx">
              该订单因渠道或者影院信息调整等特殊原因失效会导致取票失败，请联系人工客服进行退款。</text
            >
            <u-button
              type="success"
              size="mini"
              @click="handleCallPhone(ddItem)"
              >联系客服</u-button
            >
          </view>
          <view class="btns">
            <!-- <view>
              <u-button
                v-if="ddItem.status == 10"
                size="mini"
                type="warning"
                style="background-color: greenyellow"
                @click="handlePay(ddItem)"
                >去支付</u-button
              >
            </view> -->
            <view>
              <u-button
                v-if="ddItem.status == 60 && !ddItem.isfy"
                size="mini"
                type="warning"
                @click="handleGoDetail(ddItem)"
                >去取票</u-button
              >
              <u-button
                v-if="ddItem.status == 60 && ddItem.isfy"
                size="mini"
                type="warning"
                style="background-color: #1a73e8"
                @click="handleGoDetail(ddItem)"
              >
                查看已取票信息</u-button
              >
            </view>
            <view
              v-if="
                (ddItem.orderThirdParty.orderStatus == 'CLOSE' &&
                  ddItem.status == 20) ||
                (ddItem.orderThirdParty.orderStatus == 'GENERATE_FAIL' &&
                  ddItem.status == 20)
              "
            >
              <u-button
                size="mini"
                type="error"
                @click="handleRefund(ddItem.id)"
                >发起退款</u-button
              >
            </view>
          </view>
        </view>
        <!-- 返回顶部按钮 -->
        <u-back-top :scroll-top="scrollTop"></u-back-top>
      </template>
      <view v-else style="color: #999; text-align: center; font-size: 32rpx"
        >暂无订单</view
      >
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { browserVersion } from '@/utils/common'
import { onLoad, onShow, onReady, onPageScroll } from '@dcloudio/uni-app'
import { baseApi, productApi, orderApi } from '@/api'
import { useUserStore, useMovieStore, useShopInfoStore } from '@/store'
import { formatTimestamp, dateFormat } from '@/utils/index'
import { calculateStopShowTime } from '../../components/movieUtil'
const scrollTop = ref(0)
const isApp = ref(false)
const orderArr = ref<any>([])
const userStore = useUserStore()
const movieStore = useMovieStore()
const shopStore = useShopInfoStore()
const shopInfoStore = useShopInfoStore()
const { accessToken, useShareCode } = storeToRefs(userStore)
const stateList = ref<any>([
  {
    id: `${10},${20},${60},${90},${91}`,
    name: '全部'
  },
  {
    id: 10,
    name: '待支付'
  },
  {
    name: '待出票',
    id: 20
  },
  {
    name: '已出票',
    id: 60
  },
  {
    name: '已取消',
    id: `${90},${91}`
  },
  {
    name: '已退款',
    id: 92
  }
])
const current = ref(0)
onLoad(() => {
  isApp.value = shopStore.isApp
})
onShow(() => {
  handleGetOrder()
})

// 处理文字
const handleText = (zt: any, ddzt: any) => {
  let str = ''
  switch (zt) {
    case 10:
      str = '待支付'
      break
    case 20:
      str = '待出票'
      break
    case 60:
      str = '已出票'
      break
    case 90:
    case 91:
      str = '已取消'
      break
    case 92:
      str = '已退款'
      break
  }
  if ((zt == 20 && ddzt == 'CLOSE') || (zt == 20 && ddzt == 'GENERATE_FAIL')) {
    str = '出票失败'
  }

  return str
}
// 处理付款文字
const handleFkwz = (zt: any) => {
  let str = ''
  switch (zt) {
    case 10:
      str = '待付款'
      break
    case 90:
    case 91:
      str = '应付款'
      break
    default:
      str = '实付款'
  }
  return str
}
// 点击日期
const handleOrderChange = (index: any) => {
  current.value = index
  handleGetOrder()
}
// 获取订单列表
const handleGetOrder = async () => {
  const nowTime = new Date() // 获取当前时间
  uni.showLoading({ title: '加载中', mask: true })
  const navItem = stateList.value[current.value]
  // console.log('navItem', navItem)
  try {
    let tempObj = {
      pageIndex: 1,
      detail: true,
      statuses: navItem.id,
      userId: userStore.userInfo.id,
      otherColumns: 'user',
      integralsRuleId: 7,
      shopMode: JSON.parse(uni.getStorageSync('hyType')).id
    }
    const { data } = await orderApi.orderList(tempObj).finally(() => {
      uni.hideLoading()
    })
    orderArr.value = data.records.map((ele: any) => {
      //已出票的才加isfy字段
      if (ele.status === 60) {
        // 计算散场时间
        const stopShowTimeStr = calculateStopShowTime(
          ele.orderThirdParty.showTime,
          ele.orderThirdParty.duration
        )
        // 将字符串转换为 Date 对象进行比较
        const stopShowTime = new Date(stopShowTimeStr.replace(' ', 'T'))
        const isfy = nowTime > stopShowTime ? true : false
        return {
          ...ele,
          isfy
        }
      }
      // 非 status=60 的情况直接返回原对象
      return ele
    })
    // console.log('获取订单列表', data)
    // console.log('orderArr', orderArr.value)
  } catch (e) {
    console.log('获取订单列表错误')
  }
}
// 点击去支付
const handlePay = (ddItem: any) => {
  // console.log('dd', ddItem)
  if (ddItem) {
    if (isApp.value) {
      const u = browserVersion()
      if (u.iPhone) {
        // @ts-ignore
        window.JSBridge.invoke('goPay', {
          orderId: ddItem.id,
          money: ddItem.payMoney
        })
        shopInfoStore.setIsApp(false)
        return
      } else if (u.isAndroid) {
        // @ts-ignore
        if (window?.Android) {
          // @ts-ignore
          window?.Android?.goPay(ddItem.id, ddItem.payMoney)
          shopInfoStore.setIsApp(false)
        }
        return
      }
    } else {
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${ddItem.id}`
    }
  }
}
// 点击去取票
const handleGoDetail = (ddItem: any) => {
  // console.log('dd', ddItem)
  movieStore.setSelectedOrder(ddItem)
  uni.navigateTo({ url: `/packageF/pages/ticketCodeDetails/index` })
}
// 点击退票
const handleRefund = (ddid: any) => {
  uni.showModal({
    title: '提示',
    content:
      '是否确定要退款?(退款不会立即到账,系统最晚会在1-2天内提交客服支付处理)',
    success({ confirm, cancel }) {
      if (confirm) {
        const { data, code, msg } = orderApi.orderUpdate({
          id: ddid,
          status: 92
        })
        // console.log(data, code, '退款详情')
        if (code) {
          if (code == 200) {
            uni.showToast({
              title: '退款成功'
            })
          } else {
            uni.showToast({
              icon: 'error',
              title: `退款失败请稍后重试`
            })
          }
        }

        setTimeout(() => {
          //刷新
          handleGetOrder()
        }, 5000)
      } else {
        console.log('取消')
      }
    }
  })
}
//返回顶部,所在的父盒子不能设置高度
onPageScroll((e: any) => {
  scrollTop.value = e.scrollTop
})
// 点击盒子
const handleClickItem = (ddItem: any) => {
  // console.log('dd', ddItem)
  // 已出票的情况跳转取票详情页面
  if (ddItem.status == 60) {
    handleGoDetail(ddItem)
  } else {
    uni.navigateTo({
      url: `/packageF/pages/appOrderDetail/index?orderId=${ddItem.orderNo}`
    })
  }
}
// 点击联系客服
const handleCallPhone = (ddItem: any) => {
  let phone = ''
  switch (ddItem.shopMode) {
    case 1:
      phone = '13808042693'
      break
    case 4:
      phone = '18349389439'
      break
    case 6:
      phone = '19141914176'
  }
  // 判断是否为 H5 端
  if (uni.getSystemInfoSync().platform === 'web') {
    // 复制号码到剪贴板
    uni.setClipboardData({
      data: phone,
      success: () => {
        uni.showToast({ title: '号码已复制，请手动拨号', icon: 'none' })
      }
    })
  } else {
    // 非 H5 端，正常唤起拨号
    uni.makePhoneCall({ phoneNumber: phone })
  }
}
</script>

<style lang="scss" scoped>
.top {
  margin-bottom: 20rpx;
}
.footer {
  .item {
    width: 702rpx;
    // height: 298rpx;
    background: #ffffff;
    border-radius: 8rpx;
    padding: 20rpx;
    margin: 0 auto;
    margin-bottom: 20rpx;
    .item-t,
    .item-b {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .item-t {
      font-size: 24rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    .item-b {
      margin-bottom: 10rpx;
      .item-l {
        width: 152rpx;
        height: 232rpx;
        background: #d8d8d8;
        border-radius: 8rpx;
        //border: 2rpx solid #979797;
        margin-right: 20rpx;
      }
      .item-r {
        position: relative;
        flex-grow: 1;
        // height: 232rpx;
        display: flex;
        align-items: center;
        font-size: 24rpx;
        .nr {
          height: 100%;
          width: 0rpx;
          flex-grow: 1;
          .bt {
            font-size: 32rpx;
            color: #000;
            font-weight: bold;
            margin-bottom: 20rpx;
          }
          .tswz {
            text-align: right;
            .jq {
              font-family: 32rpx;
              color: #000;
              font-weight: bold;
            }
          }
        }
        .fybox {
          position: absolute;
          top: 0rpx;
          right: 0rpx;
        }
      }
    }
    .btns {
      width: 100%;
      text-align: right;
    }
  }
  .hswz {
    color: #999;
    font-size: 24rpx;
  }
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
</style>
